//
//  KKPhotosManager+Library.m
//  KKPhotosKitDemo
//
//  Created by liaozhenming on 2017/8/30.
//  Copyright © 2017年 liaozhenming. All rights reserved.
//

#import "KKPhotosManager+Library.h"
#import "KKPhotosManager+Private.h"
#import "KKPhotosManager+Preview.h"

#pragma mark - _KKPhotosItemCollectionFooterView methods
@interface _KKPhotosItemCollectionFooterView : UICollectionReusableView
@property (nonatomic, strong) UILabel *kk_titleLabel;
@end

@implementation _KKPhotosItemCollectionFooterView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: CGRectMake(0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), CGRectGetHeight(frame))];
    if (self) {
        
        _kk_titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, CGRectGetHeight(self.bounds) - 30, CGRectGetWidth(self.bounds), 20)];
        _kk_titleLabel.textAlignment = NSTextAlignmentCenter;
        _kk_titleLabel.textColor = [UIColor lightGrayColor];
        _kk_titleLabel.font = [UIFont systemFontOfSize: 16];
        [self addSubview: _kk_titleLabel];
    }
    return self;
}

@end

@interface _KKPhotosItemCollectionViewCell : UICollectionViewCell
@property (nonatomic, strong) UIImageView *img_item;

@property (nonatomic, strong) UIView *shadeView;    /**<遮罩层*/
@property (nonatomic, strong) PHAsset *assetItem;

@property (nonatomic, strong) UIImageView *img_selected;

@end

@implementation _KKPhotosItemCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        _img_item = [[UIImageView alloc] initWithFrame: [self bounds]];
        _img_item.contentMode = UIViewContentModeScaleAspectFill;
        _img_item.clipsToBounds = YES;
        [self addSubview: _img_item];
        
        _shadeView = [[UIView alloc] initWithFrame: [self bounds]];
        _shadeView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.5];
        _shadeView.hidden = true;
        [self addSubview: _shadeView];
        
        NSString *imagePath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent: @"KKPhotosKit.bundle/Images/kk_item_status_selected@3x.png"];
        
        _img_selected = [[UIImageView alloc] initWithFrame: CGRectMake(CGRectGetWidth(self.bounds) - 26, 2, 24, 24)];
        _img_selected.layer.cornerRadius = 12.0;
        _img_selected.backgroundColor = [UIColor whiteColor];
        _img_selected.layer.masksToBounds = true;
        _img_selected.image = [UIImage imageWithContentsOfFile: imagePath];
        [self addSubview: _img_selected];
    }
    return self;
}

- (void)setAssetItem:(PHAsset *)assetItem {
    if (_assetItem != assetItem) {
        _assetItem = assetItem;
        
        __weak UIImageView *weakImageView = self.img_item;
        [KKPhotosManager kk_getThumbImageForAsset: _assetItem targetSize: CGSizeMake(100, 100) resultHandle:^(UIImage *image) {
            _assetItem.kk_thumbImage = image;
            weakImageView.image = image;
        }];
    }
    
    bool isOwner = [[_KKPhotosDataManger manager] kk_isEqualItem: _assetItem];
    _shadeView.hidden = !isOwner;
    _img_selected.hidden = !isOwner;
}

@end

#pragma mark - KKPhotosItemsCollectionViewController Class
@interface _KKPhotosItemsCollectionViewController : UICollectionViewController
+ (_KKPhotosItemsCollectionViewController*)collectionViewController;

@property (nonatomic, strong) NSArray *arr_photosItems;
@property (nonatomic, strong) _KKPhotosGroupItem *groupItem;

@property (nonatomic, strong) UIButton *btn_original;

@end

@implementation _KKPhotosItemsCollectionViewController

+ (_KKPhotosItemsCollectionViewController*)collectionViewController {
    
    CGFloat width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    CGFloat itemWidth = (width - 4 * 5) / 4.0;
    
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
    _KKPhotosItemsCollectionViewController *viewController = [[_KKPhotosItemsCollectionViewController alloc] initWithCollectionViewLayout: flowLayout];
    return viewController;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.alwaysBounceVertical = true;
    self.navigationItem.title = self.groupItem.kk_assetCollection.localizedTitle;
    
    [self private_updateNavigationItem];
    
    // Register cell classes
    [self.collectionView registerClass:[_KKPhotosItemCollectionViewCell class] forCellWithReuseIdentifier:  NSStringFromClass([_KKPhotosItemCollectionViewCell class])];
    
    [self.collectionView registerClass: [_KKPhotosItemCollectionFooterView class] forSupplementaryViewOfKind: UICollectionElementKindSectionFooter withReuseIdentifier: NSStringFromClass([_KKPhotosItemCollectionFooterView class])];
    [self private_loadAllItemsData];
}

- (void)viewDidAppear:(BOOL)animated {
    [self.navigationController setToolbarHidden: false animated: true];
    [self private_updateToolBarUI];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _arr_photosItems.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(CGRectGetWidth(collectionView.bounds), 40);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(4, 4, 4, 4);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 4.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 4.0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    _KKPhotosItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: NSStringFromClass([_KKPhotosItemCollectionViewCell class]) forIndexPath: indexPath];
    [cell setAssetItem: _arr_photosItems[indexPath.row]];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    _KKPhotosItemCollectionFooterView *footerView = nil;
    
    if ([kind isEqualToString: UICollectionElementKindSectionFooter ]){
        
        footerView = (_KKPhotosItemCollectionFooterView*)[collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier: NSStringFromClass([_KKPhotosItemCollectionFooterView class]) forIndexPath:indexPath];
        
        footerView.kk_titleLabel.text = [NSString stringWithFormat: @"共%@张照片", @(self.groupItem.kk_count)];
    }
    return footerView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    PHAsset *assetItem = _arr_photosItems[indexPath.row];
    
    _KKPhotosDataManger *manager = [_KKPhotosDataManger manager];
    if ([manager kk_isEqualItem: assetItem]) {
        [manager kk_removeItem: assetItem];
    }
    else {
        //  数量限制
        if (manager.itemMaxCount == manager.arr_photoItems.count) {
            [[KKPhotosManager kk_defaultManager] kk_showErrorMessage: [NSString stringWithFormat:@"限制选取%@张相片",@(manager.itemMaxCount)]];
            return;
        }
        [manager kk_addItem: assetItem];
    }
    [collectionView reloadItemsAtIndexPaths: @[indexPath]];
    [self private_updateToolBarUI];
}

#pragma mark - Private methods
- (void)private_loadAllItemsData {
    //  获取所有的图片item
    
    NSMutableArray *tmp_arrItems = [NSMutableArray array];
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection: self.groupItem.kk_assetCollection options:nil];
    for (PHAsset *asset in assets) {
        [tmp_arrItems addObject: asset];
    }
    _arr_photosItems = [NSArray arrayWithArray: tmp_arrItems];
    [self.collectionView reloadData];
}

- (void)private_updateNavigationItem {
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style: UIBarButtonItemStylePlain target: self action:@selector(action_cancel:)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)private_updateToolBarUI {
    
    NSInteger imageCount = [[_KKPhotosDataManger manager] arr_photoItems].count;
    
    UIBarButtonItem *previewItem = [[UIBarButtonItem alloc] initWithTitle:@"预览" style: UIBarButtonItemStylePlain target: self action:@selector(action_preview:)];
    previewItem.enabled = imageCount;
    
    UIBarButtonItem *originalItem;
    {
        NSString *normal_imagePath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent: @"KKPhotosKit.bundle/Images/kk_item_status_normal_16@3x.png"];
        
        NSString *selected_imagePath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent: @"KKPhotosKit.bundle/Images/kk_item_status_selected_16@3x.png"];
        
        UIButton *btn_original = [UIButton buttonWithType: UIButtonTypeCustom];
        btn_original.frame = CGRectMake(0, 0, 60, 30);
        btn_original.titleLabel.font = [UIFont systemFontOfSize: 17];
        [btn_original setTitle: @"原图" forState: UIControlStateNormal];
        [btn_original setTitleColor: [KKPhotosManager kk_getMainColor] forState: UIControlStateNormal];
        [btn_original setTitleColor: [KKPhotosManager kk_getMainColor] forState: UIControlStateSelected];
        [btn_original setImage: [UIImage imageWithContentsOfFile: normal_imagePath] forState: UIControlStateNormal];
        [btn_original setImage: [UIImage imageWithContentsOfFile: selected_imagePath] forState: UIControlStateSelected];
        [btn_original addTarget: self action: @selector(action_original:) forControlEvents: UIControlEventTouchUpInside];
        originalItem = [[UIBarButtonItem alloc] initWithCustomView: btn_original];
        self.btn_original = btn_original;
        [self.btn_original setSelected: [KKPhotosManager kk_defaultManager].isOriginal];
    }
    
    UIBarButtonItem *sendItem = nil;
    if (imageCount == 0) {
        sendItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style: UIBarButtonItemStylePlain target: nil action: nil];
    }
    else {
        NSString *title = [NSString stringWithFormat: @"发送(%@/%@)",@(imageCount),@([[_KKPhotosDataManger manager] itemMaxCount])];
        sendItem = [[UIBarButtonItem alloc] initWithTitle:title style: UIBarButtonItemStylePlain target: self action: @selector(action_send:)];
    }
    sendItem.enabled = imageCount;
    
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil];
    
    [self.navigationController.toolbar setItems: @[previewItem, spaceItem,originalItem,spaceItem, sendItem]];
}

#pragma mark - Action methods

- (void)action_original:(id)sender {
    
    if ([KKPhotosManager kk_defaultManager].isOriginal) {
        [KKPhotosManager kk_defaultManager].isOriginal = false;
    }
    else {
        [KKPhotosManager kk_defaultManager].isOriginal = true;
    }
    [self.btn_original setSelected: [KKPhotosManager kk_defaultManager].isOriginal];
}

- (void)action_send:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName: KKPhotosManager_Event_Save_Notification object: nil];
    [self.navigationController dismissViewControllerAnimated: true completion: nil];
}

- (void)action_cancel:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName: KKPhotosManager_Event_Cancel_Notification object: nil];
    [self.navigationController dismissViewControllerAnimated: true completion: nil];
}

- (void)action_preview:(id)sender {
    [KKPhotosManager kk_previewImagesWithPhotoAssets: [[_KKPhotosDataManger manager] arr_photoItems] targetVC: self];
}

@end

#pragma mark - KKPhotosGroupTableViewCell Class
@interface _KKPhotosGroupTableViewCell : UITableViewCell
@property (nonatomic, strong)_KKPhotosGroupItem *groupItem;

@property (nonatomic, strong) UIImageView *img_item;
@property (nonatomic, strong) UILabel *lab_itemName;
@end

@implementation _KKPhotosGroupTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle: style reuseIdentifier: reuseIdentifier];
    if (self) {
        _img_item = [[UIImageView alloc] initWithFrame: CGRectMake(15, 5, 50, 50)];
        [self.contentView addSubview: _img_item];
        
        _lab_itemName = [[UILabel alloc] initWithFrame: CGRectMake(70, CGRectGetHeight(self.frame)/2.0 - 10, 100, 20)];
        _lab_itemName.font = [UIFont systemFontOfSize: 15];
        _lab_itemName.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
        [self.contentView addSubview: _lab_itemName];
    }
    return self;
}

- (void)setGroupItem:(_KKPhotosGroupItem *)groupItem {
    if (_groupItem != groupItem) {
        _groupItem = groupItem;
        NSString *groupName = _groupItem.kk_assetCollection.localizedTitle;
        _lab_itemName.text = [NSString stringWithFormat: @"%@ (%@)", groupName, @(_groupItem.kk_count)];
        [_lab_itemName sizeToFit];
        
        __weak UIImageView *weakImageView = self.img_item;
        [KKPhotosManager kk_getThumbImageForAsset: _groupItem.kk_firstItem targetSize: CGSizeMake(100, 100) resultHandle:^(UIImage *image) {
            weakImageView.image = image;
        }];
    }
}
@end

#pragma mark - KKPhotosGroupTableViewController Class
@interface _KKPhotosGroupTableViewController : UITableViewController
@property (nonatomic, strong) NSArray *arr_photosGroup;
@end

@implementation _KKPhotosGroupTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"选择相片";
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel target: self action:@selector(action_cancel:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self init_tableViewUI];
    [self private_loadAllGroupsData];
}

- (void)viewDidAppear:(BOOL)animated {
    [self.navigationController setToolbarHidden: true animated: true];
}

#pragma mark - Init methods
- (void)init_tableViewUI {
    
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = 60.0;
    
    [self.tableView registerClass: [_KKPhotosGroupTableViewCell class] forCellReuseIdentifier: NSStringFromClass([_KKPhotosGroupTableViewCell class])];
    
    UIRefreshControl *refreshControl = [UIRefreshControl new];
    [refreshControl addTarget: self action: @selector(private_loadAllGroupsData) forControlEvents: UIControlEventValueChanged];
    self.refreshControl = refreshControl;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arr_photosGroup.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _KKPhotosGroupTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: NSStringFromClass([_KKPhotosGroupTableViewCell class]) forIndexPath: indexPath];
    cell.groupItem = _arr_photosGroup[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _KKPhotosItemsCollectionViewController *itemsCollectionViewController = [_KKPhotosItemsCollectionViewController collectionViewController];
    itemsCollectionViewController.groupItem = _arr_photosGroup[indexPath.row];
    [self.navigationController pushViewController: itemsCollectionViewController animated: true];
}

#pragma mark - Action methods
- (void)action_cancel:(id)sender {
    [self.navigationController dismissViewControllerAnimated: true completion: nil];
}

#pragma mark - Private methods
- (void)private_loadAllGroupsData {
    //  获取所有的图片组
    NSMutableArray *arr_groupItems = [NSMutableArray array];
    {
        PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
        NSInteger count = smartAlbums.count;
        for (NSInteger index = 0; index < count; index++) {
            PHAssetCollection *assetCollection = [smartAlbums objectAtIndex: index];
            PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
            if (assets.count == 0) {
                break;
            }
            
            _KKPhotosGroupItem *item = [[_KKPhotosGroupItem alloc] initWithAssetCollection: assetCollection withItemCounts: assets.count];
            [arr_groupItems insertObject: item atIndex: 0];
        }
    }
    
    {
        //  用户创建的相册
        PHFetchResult *userCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
        NSInteger count = userCollections.count;
        for (NSInteger index = 0; index < count; index++) {
            PHAssetCollection *assetCollection = [userCollections objectAtIndex: index];
            PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
            if (assets.count == 0) {
                break;
            }
            _KKPhotosGroupItem *item = [[_KKPhotosGroupItem alloc] initWithAssetCollection: assetCollection withItemCounts: assets.count];
            [arr_groupItems addObject: item];
        }
    }
    
    self.arr_photosGroup = [NSArray arrayWithArray: arr_groupItems];
    [self.refreshControl endRefreshing];
    [self.tableView reloadData];
}

@end

#pragma mark - KKPhotosManager (Library) Class
@implementation KKPhotosManager (Library)

- (void)kk_takePictureFromLibrary {
     
    _KKPhotosGroupTableViewController *groupTableViewController = [_KKPhotosGroupTableViewController new];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController: groupTableViewController];
    [[self kk_rootViewController] presentViewController: navigationController animated: true completion: nil];
}

@end
